package com.irdstudio.apicenter.frame.maker;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.wc.SVNStatus;
import org.tmatesoft.svn.core.wc.SVNStatusType;

import com.irdstudio.apicenter.console.startup.MacmsRoot;
import com.irdstudio.apicenter.console.util.MacmsConstants;
import com.irdstudio.apicenter.core.dvo.RspValue;
import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.core.jdbc.container.DataList;
import com.irdstudio.apicenter.frame.maker.dm.SPageBase;
import com.irdstudio.apicenter.frame.maker.dm.SPageParamTag;
import com.irdstudio.apicenter.frame.maker.engine.ICodeGenerator;
import com.irdstudio.apicenter.frame.maker.engine.velocity.VelocityCodeGenerator;

/**
 * 按页面来制作生成代码
 * @author guangming.li
 * @version 1.0
 * @date 2015-12-22
 */
public class PageMaker {

	private JdbcBaseDAO jdbcBaseDAO;
	private String pageId;
	private DataList moduleParamList;
	private final Logger logger = LoggerFactory.getLogger(PageMaker.class);

	public PageMaker(JdbcBaseDAO jdbcBaseDAO, String pageId, DataList moduleParamList) {
		this.jdbcBaseDAO = jdbcBaseDAO;
		this.pageId = pageId;
		this.moduleParamList = moduleParamList;
	}
	
	public PageMaker(JdbcBaseDAO jdbcBaseDAO, String pageId) {
		this.jdbcBaseDAO = jdbcBaseDAO;
		this.pageId = pageId;
	}

	public RspValue make(String appId) throws IOException {
		return createPageCode(appId);
		/*// 获取页面基本定义信息
		SPageBase pageBase = jdbcBaseDAO.findBean(SPageBase.class,
				new Object[] { pageId });

		if (pageBase == null) {
			return new RspValue("未找到页面基础信息定义!");
		}

		this.logger.info("页面[" + pageBase.getPageId() + "],名称["
				+ pageBase.getPageName() + "],页面制作 方式["
				+ pageBase.getPageMakeMode() + "],模板["
				+ pageBase.getTemplateId() + "]");

		// 获取页面参数信息
		DataList pageParamList = new DataList(jdbcBaseDAO
				.findMapList("select * from s_page_param_main where page_id=?",
						new Object[] { pageId }));

		// 判断是使用模板生成还是直接使用固定的页面
		if (MacmsConstants.PAGE_MAKE_MODE_TEMPLATE.equals(pageBase
				.getPageMakeMode())) {
			// 合并模块参数与页面参数,一起为模板生成代码服务
			return generatePageFromTemplate(pageBase, moduleParamList,
					pageParamList);
		} else if (MacmsConstants.PAGE_MAKE_MODE_CUSTOM.equals(pageBase
				.getPageMakeMode())) {
			// 根据自定义页面生成页面（复制）
			return generatePageFromCustom(pageBase);

		} else {
			return new RspValue("未配置正确的页面制作方式!");
		}*/
	}
	
	public RspValue createPageCode(String appId) throws IOException {
		// 获取页面基本定义信息
		SPageBase pageBase = jdbcBaseDAO.findBean(SPageBase.class,
				new Object[] { pageId });

		if (pageBase == null) {
			return new RspValue("未找到页面基础信息定义!");
		}
		this.logger.info("页面[" + pageBase.getPageId() + "],名称["
				+ pageBase.getPageName() + "],页面制作 方式["
				+ pageBase.getPageMakeMode() + "],模板["
				+ pageBase.getTemplateId() + "]");
		//获取页面所在的模块信息
		List<Map<String, Object>> moduleList = jdbcBaseDAO.findMapList("select * from s_module_page a inner join app_frame_module b on a.module_id=b.module_id inner join s_module_base c on c.module_id=b.module_id "+
"where a.page_id=? and b.app_id=?", new Object[] { pageId, appId });
		String moduleId = "";
		if(moduleList != null && moduleList.size() > 0){
			moduleId = moduleList.get(0).get("module_id").toString();
		}
		// 获取页面参数信息
		List<Map<String, Object>> pageList = jdbcBaseDAO.findMapList("select * from s_page_param_main where page_id=?",
						new Object[] { pageId });
		// 获取页面标签参数信息
		/*List<Map<String, Object>> tagList = jdbcBaseDAO.findMapList("select * from s_page_param_tag where page_id=?",
						new Object[] { pageId });*/
		//获取页面对应的模板文件
		List<Map<String, Object>> tempFileList = jdbcBaseDAO.findMapList("select * from s_template_file where template_id=?",
				new Object[] { pageBase.getTemplateId() });
		// 获取页面标签参数信息
		Map<String, List<SPageParamTag>> tagGridMap = new HashMap<String, List<SPageParamTag>>();
		List<SPageParamTag> gridList = null;
		if(pageList != null && pageList.size() > 0){
			SPageParamTag tag = null;
			for(int i=0;i<pageList.size();i++){
				if("02".equals(pageList.get(i).get("template_param_type"))){
					List<Map<String, Object>> tagGridList = jdbcBaseDAO.findMapList("select * from s_page_param_tag where page_id=? and template_param_code=?",
							new Object[] { pageId, pageList.get(i).get("template_param_code")});
					gridList = new ArrayList<SPageParamTag>();
					if(tagGridList != null && tagGridList.size() > 0){
						for(Map<String, Object> mp : tagGridList){
							tag = new SPageParamTag();
							tag.setTagName(mp.get("tag_name").toString());
							tag.setTagType(mp.get("tag_type").toString());
							tag.setTagValueSrc(mp.get("tag_value_src").toString());
							gridList.add(tag);
						}
						tagGridMap.put(pageList.get(i).get("template_param_code").toString(), gridList);
					}
				}
			}
		}
		DataList pageParamList = new DataList(pageList);
		// 判断是使用模板生成还是直接使用固定的页面
		if (MacmsConstants.PAGE_MAKE_MODE_TEMPLATE.equals(pageBase.getPageMakeMode())) {
			// 合并模块参数与页面参数,一起为模板生成代码服务
			return generatePageFromTemplate2(pageBase, null, pageParamList, tempFileList, tagGridMap, new String[]{appId, moduleId, pageId});
		} else if (MacmsConstants.PAGE_MAKE_MODE_CUSTOM.equals(pageBase.getPageMakeMode())) {
			// 根据自定义页面生成页面（复制）
			return generatePageFromCustom(pageBase);
		} else {
			return new RspValue("未配置正确的页面制作方式!");
		}
	}
	
	/**
	 * 根据模板生成页面
	 * 
	 * @param pageBase
	 * @param moduleParamList
	 * @param pageParamList
	 * @throws IOException 
	 */
	/*private RspValue generatePageFromTemplate(SPageBase pageBase,
			DataList moduleParamList, DataList pageParamList) throws IOException {
		ICodeGenerator veloctiyGenerator = new VelocityCodeGenerator();
		veloctiyGenerator.generate("0090020001/login.html.vm", pageParamList, "", null, null);
		return new RspValue("0", "代码生成成功");
	}*/
	
	/**
	 * 根据模板生成页面2
	 * 
	 * @param pageBase
	 * @param moduleParamList
	 * @param pageParamList
	 * @throws IOException 
	 */
	private RspValue generatePageFromTemplate2(SPageBase pageBase,
			DataList moduleParamList, DataList pageParamList, List<Map<String, Object>> list,Map<String, List<SPageParamTag>> tagGridMap,
			String[] module) throws IOException {
		RspValue rv = null;
		File[] files = null;
		if(list != null && list.size() > 0){
			files = new File[list.size()];
			for(int i=0;i<list.size();i++){
				Map<String, Object> map = list.get(i);
				ICodeGenerator veloctiyGenerator = new VelocityCodeGenerator();
				File fl = veloctiyGenerator.generate(map.get("template_file").toString()+","+map.get("file_type").toString(), pageParamList, "", tagGridMap, module);
				files[i] = fl;
			}
			//提交新增的文件
			if(files != null && files.length > 0){
				List<File> updateList=new ArrayList<File>(); 
				List<File> addList=new ArrayList<File>(); 
				for(File fe : files){
					System.out.println("获取svn中指定文件的状态...");
					SVNStatus status = MacmsRoot.getSvnProjectService().getFileStatus(module[0], fe);
					System.out.println("文件状态："+status);
					//如果此文件是新增加的则先把此文件添加到版本库，然后提交。 
					if(status == null || status.getContentsStatus()==SVNStatusType.STATUS_UNVERSIONED){ 
						addList.add(fe);
					}else{
						updateList.add(fe);
					}
				}
				if(updateList.size() > 0){
					//直接提交修改的文件
					this.logger.info("提交修改的文件到svn...");
					System.out.println("提交修改的文件到svn...");
					MacmsRoot.getSvnProjectService().commit(module[0], updateList.toArray(new File[updateList.size()]));
				}
				if(addList.size() > 0){
					//先将新增的文件
					this.logger.info("提交新增的文件到svn...");
					System.out.println("提交新增的文件到svn...");
					MacmsRoot.getSvnProjectService().commitProjectFile(module[0], addList.toArray(new File[addList.size()]));
				}
			}
			rv = new RspValue("0", "代码生成成功");
		}else{
			rv = new RspValue("未找到模板文件");
		}
		return rv;
	}
	
	/**
	 * 根据自定义页面得到页面(复制)
	 * 
	 * @param pageBase
	 */
	private RspValue generatePageFromCustom(SPageBase pageBase) {
		
		return null;
	}	
}
